package com.itlong.cloud.sdk.service.impl;

import com.itlong.cloud.POJO.PO.HotParamFlowRule;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.sdk.dao.IHotParamFlowRuleDao;
import com.itlong.cloud.sdk.service.IHotParamFlowRuleService;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotParamFlowRuleServiceImpl implements IHotParamFlowRuleService {

    @Autowired
    private IHotParamFlowRuleDao hotParamFlowRuleDao;

    @Autowired
    private MessageSender messageSender;

    @Autowired
    private RedisService redisService;


  /*  //限流缓存时间
    @Value("${" + PlatformConstants.SDK_REDIS_TIME + "}")
    private long SDK_REDIS_TIME;
*/

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<HotParamFlowRule> getHotParamFlowRule(Map<String, Object> param) {
        return hotParamFlowRuleDao.getHotParamFlowRule(param);
    }


    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer save(HotParamFlowRule hotParamFlowRule) {
        try {
            if(hotParamFlowRule !=null){
                Integer save = hotParamFlowRuleDao.save(SqlUtil.durableData(hotParamFlowRule, PlatformConstants.TABLE_SAVE));
                Map<String, Object> map = new HashMap<>();
                map.put("resourceNameUrl", hotParamFlowRule.getResourceNameUrl());

                List<HotParamFlowRule> flowRule = hotParamFlowRuleDao.getHotParamFlowRule(map);

                //2.直接更新redis
                if (save>0){
                redisService.set(hotParamFlowRule.getResourceNameUrl(),PlatformConstants.SDK_REDIS_TIME,flowRule);
                }
                return save;
            }
        } catch (Exception e) {
            throw new DataAccessException("【SDK_room_update】更新房间异常",e);
        }
        return null;
    }

    /**
     * <desc>
     * 根据参数查询限流规则
     * </desc>
     *
     * @param param
     * @Author chengshican
     * @Date 2020-11-24 10:02
     * @Param
     * @Return
     * @Exception
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public HotParamFlowRule getFlowRuleByParam(Map<String, Object> param) {
        return hotParamFlowRuleDao.getFlowRuleByParam(param);
    }
}
